/*
 * Copyright © 2022-now 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springcloud.seata.storage.service.impl;

import cn.denvie.springcloud.seata.common.model.entity.Storage;
import cn.denvie.springcloud.seata.storage.mapper.StorageMapper;
import cn.denvie.springcloud.seata.storage.service.StorageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Storage服务实现类。
 *
 * @author Denvie
 * @date 2022/4/08
 * @since 1.0.0
 */
@Slf4j
@Service
public class StorageServiceImpl extends ServiceImpl<StorageMapper, Storage> implements StorageService {

    @Override
    public Storage getByCommodityCode(String commodityCode) {
        QueryWrapper<Storage> wrapper = new QueryWrapper<>();
        wrapper.eq("commodity_code", commodityCode);
        return super.getOne(wrapper);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void deduct(String commodityCode, int count) {
        log.info("=============扣减库存=================");

        // 检查库存
        checkStock(commodityCode, count);

        log.info("开始扣减商品【{}】库存", commodityCode);
        int result = getBaseMapper().deduct(commodityCode, count);
        log.info("扣减商品【{}】库存结果:{}", commodityCode, result > 0 ? "成功" : "失败");
    }

    private void checkStock(String commodityCode, int count) {
        log.info("检查商品【{}】库存", commodityCode);

        Storage storage = getByCommodityCode(commodityCode);
        if (storage == null) {
            throw new RuntimeException("商品【" + commodityCode + "】不存在");
        }
        if (storage.getCount() < count) {
            log.warn("商品【{}】库存不足，当前库存：{}", commodityCode, count);
            throw new RuntimeException("商品【" + commodityCode + "】库存不足");
        }
    }
}
